var api = require("../../api.js"),
        utils = require("../../utils.js"),
        images = require('../../utils/images.js'),
        app = getApp(),
        is_loading = !1,
        is_no_more = !1
        var timer = 1;
Page({
    data: {
        childTabbarList: {},
        current_page: 1,
        page_count: 6,
        keyword: "",
        show_type: 0,  // 1代表显示搜索数据, 2代表显示正常列表数据，0代表默认
        tab: 1,
        sort: 1,
        cat_id: 1,    // 商品分类id
        mch_id: null,  // 商铺id
        banner_list: [],
        curIndex: 0,      // segment index 
        scrollLeft: 0,
        swiperViewHeight: 200,
        showGoodsSortView: false,  // 是否显示分类弹窗
        goodsSortViewTop: 0,      
        shopSortList: [],         // 商品分类列表
        shop: {},                 // 店铺相关数据
        searchList: {},            // 商品搜索结果 
        miaosha: null,
        coupon_list: [],
        get_coupon_list: [],
        bargain: [],
        fixSegmentView: false,    // 用于标识商品分类条目视图是否固定在顶部
        segmentViewHeight: 0,     // 商品分类条目视图的高度
        moreIcon: images.nearbyShop.moreIcon,
        moreUpIcon: images.nearbyShop.moreUpIcon,
        navigationIcon: images.nearbyShop.navigationIcon,
        qrCodeIcon: images.nearbyShop.qrCodeIcon,
        switchIcon: images.nearbyShop.switchIcon,
        locationSmallIcon: images.nearbyShop.locationSmallIcon,
        groupIcon: images.index.groupIcon,
        seckillIcon: images.index.seckillIcon,
    }, 
    onLoad: function(options) {
      app.pageOnLoad(this)
      app.editTabBar()
      if (options.mch_id) {
        // 保存子商户id，用于切换tabbar时取值
        app.globalData.mchId = options.mch_id;
        this.setData({
            mch_id: options.mch_id
        })
      } else if (options.scene) {
          // 获取扫描二维码时传的mch_id
           // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
           const scene = decodeURIComponent(options.scene)
           const data = utils.scene_decode(scene)
           if (data.mch_id) {
             this.setData({
                mch_id: data.mch_id
            })
           }
      } else if (app.globalData.mchId) {
        // 切换tabbar时，从 app.js 中获取保存的值
        this.setData({
          mch_id: app.globalData.mchId
      })
      }
      if (this.data.mch_id) {
            this.loadBannerData()
            this.loadShopData()
      } else {
        wx.showModal({
            title: "提示",
            content: "店铺id为空，店铺不存在！"
          })
      }
    },
    onShow: function() {
        app.pageOnShow(this);
    },
    onReachBottom: function() {
      if (this.data.show_type == 2) {
          this.getGoodsList();
      } 
    },
    onPageScroll(event) {
      // 在页面滚动的过程中，判断商品条目视图是否需要固定在顶部
      const that = this
      let query = wx.createSelectorQuery()
      query.select('.goods-list').boundingClientRect(ref => {
        that.setData({
          fixSegmentView: ref && ref.top <= that.data.segmentViewHeight ? true : false
        })
      }).exec()
    },
    /**
     * 获取店铺信息
     */
    loadShopData: function() {
        const that = this
        const key = "shop_data_mch_id_" + this.data.mch_id
        const cacheData = wx.getStorageSync(key)
        
        cacheData && this.setData({
            shop: cacheData.shop
        }), wx.showNavigationBarLoading(), this.setData({
            loading: !0
        })

        app.request({
            url: api.mch.shop,
            data: {
                tab: this.data.tab,
                sort: this.data.sort,
                page: 1,
                mch_id: this.data.mch_id,
                cat_id: this.data.cat_id
            },
            success: function(res) {
                1 != res.code ? 0 == res.code && (that.setData({
                        shop: res.data.shop,
                        mch_id: res.data.shop.id,
                        coupon_list: res.data.coupon_list ? res.data.coupon_list : [],
                        new_list: res.data.new_list,
                        miaosha: res.data.miaosha,
                        update_list: res.data.update_list,
                        pintuan: res.data.pintuan,
                        bargain: res.data.bargain
                    }),
                    // 动态修改标题为店铺名称
                    wx.setNavigationBarTitle({
                      title: res.data.shop.name
                    }),
                    // 加载商品分类数据
                    that.loadStoreSortData(),
                    wx.setStorageSync(key, res.data)) : wx.showModal({
                    title: "提示",
                    content: res.msg,
                    showCancel: !1,
                    success: function(showRes) {
                        showRes.confirm && wx.redirectTo({
                            url: "/mch/shop/shop"
                        })
                    }
                });
            },
            complete: function() {
               // 开启秒杀
               that.miaoshaTimer()
                wx.hideNavigationBarLoading(), that.setData({
                    loading: !1
                })
            }
        })
    },
    // 加载搜索数据
    loadData: function() {
        if (this.data.show_type == 2) {
            this.loadShopData();
            return;
        }
        if (this.data.show_type != 1) {
            console.log(this.data.show_type);
            return;
        }
        var that = this
        wx.showLoading({
            title: "加载中"
        }), app.request({
            url: api.mch.search_goods,
            method: "POST",
            data: {
                mch_id: this.data.mch_id,
                keyword: that.data.keyword,
            },
            success: function(d) {
                0 == d.code && that.setData({
                    searchList: d.data.banner_list,
                });
            },
            fail: function(d) {
                wx.showToast({
                    title: '搜索失败',
                    image: "http://runwu100.img.guoxiaoge.cn/icon-warning.png"
                });
            },
            complete: function(d) {
                wx.hideLoading();
            }
        });
    },
    // 轮播图数据
    loadBannerData: function() {
        var that = this;
        app.request({
            url: api.mch.banner,
            data: {
                mch_id: this.data.mch_id,
            },
            success: function(d) {
                0 == d.code && that.setData({
                    banner_list: d.data.banner_list[0],
                });
            }
        });
    },
    /**
     * 加载商铺分类数据 
     */
    loadStoreSortData() {
        var that = this;
        var path = "shop_cat_list_mch_id_" + this.data.shop.id,
            cacheData = wx.getStorageSync(path);
        const mchId = this.data.shop.id
        cacheData && that.setData({
            shopSortList: cacheData
        }), wx.showNavigationBarLoading(), app.request({
            url: api.mch.shop_cat,
            data: {
                mch_id: mchId
            },
            success: function(res) {
                0 == res.code && (that.setData({
                        shopSortList: res.data.list,
                        cat_id: res.data.list.length > 0 ? res.data.list[0].id : 0,
                        current_page: 0,
                        page_count: 0,
                        tab: 2,
                        sort: 0,
                        no_more: false,
                        goods_list: []
                    }),
                    // 计算分类视图的高度
                    that.computedSegmentViewHeight(),
                    // 加载第一个分类的数据
                    that.getGoodsList(), wx.setStorageSync(path, res.data.list))
            },
            complete: function() {
                wx.hideNavigationBarLoading()
            }
        })
    },
    getGoodsList: function() {
        if (this.data.shopSortList.length === 0) {
            return
        }
        var a = this;
        // waring
        // const mch_id = 24
        // const cat_id = 68
        const cat_id = this.data.cat_id
        const mch_id = this.data.shop.id
        if (3 != a.data.tab && !a.data.loading && !a.data.no_more) {
            a.setData({
                loading: !0
            });
            const page = (a.data.current_page || 0) + 1;
            console.log('page: ' + page)
            app.request({
                url: api.mch.shop,
                data: {
                    mch_id: mch_id,
                    tab: a.data.tab,
                    sort: a.data.sort,
                    page: page,
                    cat_id: cat_id,
                },
                success: function(t) {
                    0 == t.code && (1 == a.data.tab && (t.data.goods_list && t.data.goods_list.length ? (a.data.hot_list = a.data.hot_list.concat(t.data.goods_list), a.setData({
                            hot_list: a.data.hot_list,
                            current_page: page
                        })) : a.setData({
                            no_more: !0
                        })),
                        2 == a.data.tab && (t.data.goods_list && t.data.goods_list.length ? (a.data.goods_list = a.data.goods_list.concat(t.data.goods_list), a.setData({
                            goods_list: a.data.goods_list,
                            current_page: page,
                            show_type: 2
                        })) : a.setData({
                            no_more: !0
                        })))
                },
                complete: function() {
                    console.log('goods_list')
                    console.log(a.data.goods_list)
                    a.setData({
                        loading: !1
                    })
                }
            })
        }
    },
    /**
     * 商品加载更多
     */
    loadMoreGoodsData() {

    },
    inputFocus: function(t) {
        this.setData({
            show: !0
        });
    },
    inputBlur: function(t) {
        this.setData({
            show: !1
        });
    },
    inputConfirm: function(t) {
        this.onClickSearch();
    },
    inputChange: function(t) {
        this.setData({
            keyword: t.detail.value
        });
    },
    onClickSearch: function(t) {
        if (this.data.keyword) {
            this.setData({
                show_type: 1
            });
        } else {
            this.setData({
                show_type: 2
            });
        }
        this.loadData();
    },
    // 点击更多按钮，显示分类窗口
    onClickMoreButton() {
        this.setData({
            showGoodsSortView: true
        })
    },
    // 隐藏分类窗口
    onClickSortItem(event) {
        const index = parseInt(event.target.dataset.index);
        if (index !== this.data.curIndex) {
          this.switchSegmentIndex(index)
        }
        this.setData({
            showGoodsSortView: false
        })
    },
    // 隐藏分类窗口
    onClickMaskView() {
        this.setData({
            showGoodsSortView: false
        })
    },
    // 修改商品导航index
    onSwitchSegment(event) {
        const index = parseInt(event.target.dataset.index);
        if (index !== this.data.curIndex) {
            this.switchSegmentIndex(index)
        }
    },
    // 切换商品类别
    switchSegmentIndex(index) {
      this.setData({
        curIndex: index,
        cat_id: this.data.shopSortList[index].id,
        current_page: 0,
        tab: 2,
        sort: 0,
        no_more: false,
        goods_list: []
      })
      this.getGoodsList()
      // 调整item的位置，显示当前选中的item
      const that = this
      if (index > 2) {
        var query = wx.createSelectorQuery()
        query.select('.scroll-segment-view').boundingClientRect(function(res) {
          if (res) {
            that.setData({
              scrollLeft: (index - 2) * 75
            })
          }
        })
        query.exec()
      } else {
        this.setData({
          scrollLeft: 0
        })
      }
    },
    /**
     * 打开地图
     */
    goMapPage() {
      var that = this;
      wx.getSetting({
          success: function(res) {
            res.authSetting["scope.userLocation"] ? that.openLocationPage() : app.getauth({
                  content: "需要获取您的地理位置授权，请到小程序设置中打开授权！",
                  cancel: !1,
                  success: function(authRes) {
                    authRes.authSetting["scope.userLocation"] && that.openLocationPage()
                  }
              });
          }
      });
  },
    /**
     * 打开地图
     */
    openLocationPage() {
        const that = this
        wx.openLocation({
            latitude: parseFloat(that.data.shop.lat),
            longitude: parseFloat(that.data.shop.log),
            name: that.data.shop.name,
            address: that.data.shop.address
        });
    },
    miaoshaTimer: function() {
      var t = this;
      clearInterval(timer);
      t.data.miaosha && t.data.miaosha.rest_time && (timer = setInterval(function() {
          0 < t.data.miaosha.rest_time ? (t.data.miaosha.rest_time = t.data.miaosha.rest_time - 1,
              t.data.miaosha.times = t.getTimesBySecond(t.data.miaosha.rest_time), t.setData({
                  miaosha: t.data.miaosha
              })) : clearInterval(timer);
      }, 1e3));
    },
    getTimesBySecond: function(t) {
      if (t = parseInt(t), isNaN(t)) return {
          h: "00",
          m: "00",
          s: "00"
      };
      var a = parseInt(t / 3600),
          e = parseInt(t % 3600 / 60),
          i = t % 60;
      return 1 <= a && (a -= 1), {
          h: a < 10 ? "0" + a : "" + a,
          m: e < 10 ? "0" + e : "" + e,
          s: i < 10 ? "0" + i : "" + i
      };
    },
    /**
     * 在获取分类数据后，计算segment view的高度
     */
    computedSegmentViewHeight() {
      const that = this
      let query = wx.createSelectorQuery()
      query.select('.segment-view').boundingClientRect(ref => {
        that.setData({
          segmentViewHeight: ref && ref.height 
        }) 
      }).exec()
    }
});